package com.aw.guiguzi.widgets

import android.app.Activity
import android.graphics.drawable.BitmapDrawable
import android.os.Build
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.EditText
import android.widget.ImageView
import android.widget.PopupWindow
import android.widget.Spinner
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.aw.baselib.base.AwBaseConstant
import com.aw.baselib.util.AwDataUtil
import com.aw.baselib.util.AwDisplayUtil
import com.aw.baselib.util.AwPopupwindowUtil
import com.aw.baselib.util.AwRecyclerViewUtil
import com.aw.baselib.util.AwSoftKeyboardUtil
import com.aw.baselib.util.AwToastUtil
import com.aw.guiguzi.R
import com.aw.guiguzi.adapter.NumHandleInputAdapter
import com.aw.guiguzi.base.MyApp
import com.aw.guiguzi.bean.NumHandleInputResultBean
import com.aw.guiguzi.bean.NumItemBean
import com.aw.guiguzi.util.AppCacheUtil
import com.aw.guiguzi.util.CalResultUtil.getDefaultConfigBlockIndex
import com.aw.guiguzi.util.CalResultUtil.getSpecialBlockList
import com.chad.library.adapter.base.BaseQuickAdapter

class NumHandleInputPopupWindow(
    private val mActivity: Activity,
    callback: OnResultCallback?,
    dismissListener: OnDismissListener?
) : PopupWindow() {
    private val contentView: View
    private val mAdapter: NumHandleInputAdapter
    private var mList: MutableList<NumItemBean> = ArrayList()

    init {
        mList = MyApp.mAllBettingNumsList
        contentView = View.inflate(mActivity, R.layout.view_popupwindow_num_handle_input, null)
        val rcv_data = contentView.findViewById<View>(R.id.rcv_data) as RecyclerView
        val tv_block = contentView.findViewById<Spinner>(R.id.tv_block)
        val iv_close = contentView.findViewById<ImageView>(R.id.iv_close)
        val tv_submit = contentView.findViewById<TextView>(R.id.tv_submit)
        val et_resultNum = contentView.findViewById<EditText>(R.id.et_resultNum)
        val et_silverNum = contentView.findViewById<EditText>(R.id.et_silverNum)
        val et_skinNum = contentView.findViewById<EditText>(R.id.et_skinNum)
        val et_gemstoneNum = contentView.findViewById<EditText>(R.id.et_gemstoneNum)
        val et_silverNumTotal = contentView.findViewById<EditText>(R.id.et_silverNumTotal)
        val et_skinNumTotal = contentView.findViewById<EditText>(R.id.et_skinNumTotal)
        val et_gemstoneNumTotal = contentView.findViewById<EditText>(R.id.et_gemstoneNumTotal)
        et_silverNum.setText(AppCacheUtil.getBettingConfigInputSliver(false))
        et_skinNum.setText(AppCacheUtil.getBettingConfigInputSkin(false))
        et_gemstoneNum.setText(AppCacheUtil.getBettingConfigInputGemstone(false))
        et_silverNumTotal.setText(AppCacheUtil.getBettingConfigInputSliver(true))
        et_skinNumTotal.setText(AppCacheUtil.getBettingConfigInputSkin(true))
        et_gemstoneNumTotal.setText(AppCacheUtil.getBettingConfigInputGemstone(true))
        mAdapter = NumHandleInputAdapter()
        AwRecyclerViewUtil.setRecyclerViewGridlayout(
            mActivity,
            rcv_data,
            mAdapter,
            5,
            AwDisplayUtil.dip2px(mActivity, 2f)
        )
        mAdapter.addAllData(mList)
        tv_block.setSelection(getDefaultConfigBlockIndex(mActivity))
        tv_block.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>,
                view: View,
                position: Int,
                id: Long
            ) {
                setSpecialBlockView(parent.selectedItem as String)
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {}
        }
        iv_close.setOnClickListener { v: View? -> dismiss() }
        tv_submit.setOnClickListener { v: View? ->
            if (null != callback) {
                val selectList: MutableList<NumItemBean?> = ArrayList()
                for (itemBean in mList) {
                    if (itemBean.isChecked) {
                        selectList.add(itemBean)
                    }
                }
                if (AwDataUtil.isEmpty(selectList)) {
                    AwToastUtil.showShort(mActivity, "请至少选择一项数据")
                    return@setOnClickListener
                }
                if (AwDataUtil.isEmpty(et_resultNum.text.toString())) {
                    AwToastUtil.showShort(mActivity, "请输入结果数值")
                    return@setOnClickListener
                }
                if (AwDataUtil.isEmpty(et_silverNum.text.toString())
                    && AwDataUtil.isEmpty(et_skinNum.text.toString())
                    && AwDataUtil.isEmpty(et_gemstoneNum.text.toString())
                ) {
                    AwToastUtil.showShort(mActivity, "请至少输入一项下注内容")
                    return@setOnClickListener
                }
                if (AwDataUtil.isEmpty(et_silverNumTotal.text.toString())
                    && AwDataUtil.isEmpty(et_skinNumTotal.text.toString())
                    && AwDataUtil.isEmpty(et_gemstoneNumTotal.text.toString())
                ) {
                    AwToastUtil.showShort(mActivity, "请至少输入一项结果内容")
                    return@setOnClickListener
                }
                AwSoftKeyboardUtil.hideSoftKeyboard(mActivity)
                AppCacheUtil.setBettingConfigInputSliver(et_silverNum.text.toString(), false)
                AppCacheUtil.setBettingConfigInputSkin(et_skinNum.text.toString(), false)
                AppCacheUtil.setBettingConfigInputGemstone(et_gemstoneNum.text.toString(), false)
                AppCacheUtil.setBettingConfigInputSliver(et_silverNumTotal.text.toString(), true)
                AppCacheUtil.setBettingConfigInputSkin(et_skinNumTotal.text.toString(), true)
                AppCacheUtil.setBettingConfigInputGemstone(
                    et_gemstoneNumTotal.text.toString(),
                    true
                )
                val bean = NumHandleInputResultBean()
                bean.list = selectList
                bean.resultNumber = AwDataUtil.getIntValue(et_resultNum.text.toString())
                bean.silverCount = AwDataUtil.getIntValue(et_silverNum.text.toString())
                bean.skinCount = AwDataUtil.getIntValue(et_skinNum.text.toString())
                bean.gemstoneCount = AwDataUtil.getIntValue(et_gemstoneNum.text.toString())
                bean.silverCountTotal = AwDataUtil.getIntValue(et_silverNumTotal.text.toString())
                bean.skinCountTotal = AwDataUtil.getIntValue(et_skinNumTotal.text.toString())
                bean.gemstoneCountTotal =
                    AwDataUtil.getIntValue(et_gemstoneNumTotal.text.toString())
                callback.onResult(bean)
            }
            dismiss()
        }
        contentView.findViewById<View>(R.id.iv_delConfigNums).setOnClickListener { v: View? ->
            et_silverNum.setText("")
            et_skinNum.setText("")
            et_gemstoneNum.setText("")
            et_silverNumTotal.setText("")
            et_skinNumTotal.setText("")
            et_gemstoneNumTotal.setText("")
            for (itemBean in mList) {
                itemBean.isChecked = false
            }
            mAdapter.notifyDataSetChanged()
        }
        mAdapter.setOnItemClickListener { adapter: BaseQuickAdapter<*, *>, view: View?, position: Int ->
            val itemBean = adapter.getItem(position) as NumItemBean?
            itemBean!!.isChecked = !itemBean.isChecked
            mAdapter.notifyDataSetChanged()
        }
        setContentView(contentView)
        this.width = ViewGroup.LayoutParams.MATCH_PARENT
        this.height = ViewGroup.LayoutParams.WRAP_CONTENT
        this.animationStyle = com.aw.baselib.R.style.sytle_anim_pop_in_out
        this.isFocusable = true
        this.isTouchable = true
        this.isOutsideTouchable = true
        setBackgroundDrawable(BitmapDrawable())
        this.update()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            this.overlapAnchor = true
        }
        if (dismissListener == null) {
            setOnDismissListener {
                val lp = mActivity.window.attributes
                lp.alpha = AwBaseConstant.Popupwindow.POPUPWINDOW_NORMAL
                mActivity.window.attributes = lp
            }
        } else {
            setOnDismissListener(dismissListener)
        }
    }

    private fun clearAllSelect() {
        for (itemBean in mList) {
            itemBean.isChecked = false
        }
    }

    private fun setSpecialBlockView(block: String) {
        clearAllSelect()
        val list = getSpecialBlockList(block)
        for (itemBean in mList) {
            if (list.contains(itemBean.name)) {
                itemBean.isChecked = true
            }
        }
        mAdapter.notifyDataSetChanged()
    }

    /**
     * 展示窗口
     */
    fun show(parent: View?) {
        val lp = mActivity.window.attributes
        lp.alpha = AwBaseConstant.Popupwindow.POPUPWINDOW_DARK
        mActivity.window.attributes = lp
        this.showAsDropDown(parent, 0, 0)
    }

    fun showAsLocation(parent: View?) {
        val lp = mActivity.window.attributes
        lp.alpha = AwBaseConstant.Popupwindow.POPUPWINDOW_DARK
        mActivity.window.attributes = lp
        val windowPos = AwPopupwindowUtil.calculatePopWindowPos(parent, contentView)
        val xOff = 20 // 可以自己调整偏移
        windowPos[0] -= xOff
        showAtLocation(parent, Gravity.TOP or Gravity.START, windowPos[0], windowPos[1])
    }

    fun showAsLocationNoAlpha(parent: View?) {
        val windowPos = AwPopupwindowUtil.calculatePopWindowPos(parent, contentView)
        val xOff = 20 // 可以自己调整偏移
        windowPos[0] -= xOff
        showAtLocation(parent, Gravity.TOP or Gravity.START, windowPos[0], windowPos[1])
    }

    fun showAsLocationBottom(parent: View?) {
        val lp = mActivity.window.attributes
        lp.alpha = AwBaseConstant.Popupwindow.POPUPWINDOW_DARK
        mActivity.window.attributes = lp
        showAtLocation(parent, Gravity.BOTTOM or Gravity.CENTER_HORIZONTAL, 0, 0)
    }

    /**
     * calendar菜单选择监听接口
     */
    interface OnResultCallback {
        fun onResult(bean: NumHandleInputResultBean?)
    }
}